package com.xiaoshuidi.cloud.module.finance.job.invoice;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xiaoshuidi.cloud.framework.tenant.core.job.TenantJob;
import com.xiaoshuidi.cloud.module.contract.api.ContractRentOrderApi;
import com.xiaoshuidi.cloud.module.finance.dal.dataobject.invoice.BaiwangInvoiceLogDO;
import com.xiaoshuidi.cloud.module.finance.dal.dataobject.invoice.InvoiceDO;
import com.xiaoshuidi.cloud.module.finance.dal.mysql.invoice.BaseInvoiceMapper;
import com.xiaoshuidi.cloud.module.finance.enums.invoice.BwServiceEnum;
import com.xiaoshuidi.cloud.module.finance.util.invoice.Base64Util;
import com.xiaoshuidi.cloud.module.finance.util.invoice.BwServiceUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@TenantJob
@RefreshScope
public class InvoiceJob {
    @Resource
    private BaseInvoiceMapper invoiceMapper;
    @Resource
    private ContractRentOrderApi contractRentOrderApi;


    /**
     * 查询发票结果
     */
    @XxlJob("fpStatusSearch")
    public void fpStatusSearch() {
        log.info("=================== 查询发票结果 - 执行开始 ===================");
        LambdaQueryWrapper<InvoiceDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(InvoiceDO::getStatus, "1");
        wrapper.isNotNull(InvoiceDO::getOrderNo);
        List<InvoiceDO> invoiceList = invoiceMapper.selectList(wrapper);
        for (InvoiceDO invoice : invoiceList) {
            List<Long> orderList = new ArrayList<>();
            String[] orderIds = invoice.getOrderNo().split(",");
            for (String orderId : orderIds) {
                orderList.add(Long.valueOf(orderId));
            }
            Map<String, String> map = new HashMap<>();
            map.put("djbh", invoice.getSeqNo());
            String result = BwServiceUtil.fpStatusSearch(map);
            log.info("百旺发票开票结果查询【" + invoice.getSeqNo() + "】：" + JSON.toJSONString(result));
            com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(result);
            if (StringUtils.equals(jsonObject1.get("code").toString(), "0")) {
                String info = Base64Util.decode(jsonObject1.getString("data"));
                cn.hutool.json.JSONObject jsonObject2 = JSONUtil.parseObj(info);
                invoice.setStatus("2");
                invoice.setInvoiceCode(jsonObject2.getStr("fpdm"));
                invoice.setInvoiceNumber(jsonObject2.getStr("qdfphm"));
                invoice.setPdfUrl(jsonObject2.getStr("pdf"));
                contractRentOrderApi.orderInvoiceStatus(orderList, invoice.getId(), 2);
            } else {
                invoice.setStatus("3");
                invoice.setErrorReason(JSON.toJSONString(result));
                contractRentOrderApi.orderInvoiceStatus(orderList, invoice.getId(), 3);
            }
            invoiceMapper.updateById(invoice);

            BaiwangInvoiceLogDO.builder()
                    .interfaceName(BwServiceEnum.FP_STATUS_SEARCH.getSummary())
                    .seqNo(invoice.getSeqNo())
                    .dataParams(invoice.getSeqNo())
                    .resultData(result)
                    .build();
        }
        log.info("=================== 查询发票结果 - 执行结束 ===================");
    }

}
